import Vue from 'vue'
import loadingComponent from './index.vue'


const LoadingConstructor = Vue.extend(loadingComponent)
let loadingPool = []

let getAnInstance = () => {
    if (loadingPool.length > 0) {
        let instance = loadingPool[0]
        loadingPool.splice(0, 1)
        return instance
    }
    return new LoadingConstructor({
        el: document.createElement('div')
    })
}

let returnAnInstance = instance => {
    if (instance) {
        loadingPool.push(instance)
    }
}

let removeDom = event => {
    if (event.target.parentNode) {
        event.target.parentNode.removeChild(event.target)
    }
}

LoadingConstructor.prototype.close = function () {
    this.visible = false
    this.$el.addEventListener('transitionend', removeDom)
    returnAnInstance(this)
}


let loading = () => {
    let instance = getAnInstance()
    document.body.appendChild(instance.$el)
    Vue.nextTick(function () {
        instance.visible = true
    })
    return instance
}

export default loading
